package rus.webapp.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import rus.model.ContentImage;
import rus.model.Shop;
import rus.service.ContentImageManager;
import rus.service.ShopManager;

public class ShopForm extends BasePage implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -2142890837310996179L;
	
	private Shop shop = new Shop();
	private ShopManager shopManager;
	private ContentImageManager contentImageManager;
	private UploadedFile file;
	private Integer id;
	
	public String callCreate(){
		log.info("Call creating new shop");
		shop = new Shop();
		return SUCCESS;
	}
	
	public String createShop() throws IOException{
		ContentImage contentImage = null;
		byte[] byteArray = null;
		
		if(getFile() != null){
		contentImage =	new ContentImage();
		
		InputStream stream = file.getInputStream();
		ByteArrayOutputStream bAOut = new ByteArrayOutputStream();
		int c;
		while ((c = stream.read()) != -1) {
			bAOut.write((char) c);
		}
			byteArray = bAOut.toByteArray();
			contentImage.setURI(StringUtils.replace(StringUtils.lowerCase("shop/" + shop.getName()), " ", "/"));
			contentImage.setData(byteArray);
			getContentImageManager().saveContentImage(contentImage);
		}		
		
		
		shop.setURL(validateURL(shop.getURL()));
		shop.setLogo(contentImage);
		shopManager.saveShop(shop);
		
		log.info("New shop was successfully added......");
		return SUCCESS;
	}
	
	public List<Shop> getShopList(){
		return shopManager.getAll();
	}	
	
	public String callEditShop(){
		setShop(shopManager.getShopById(getId()));
		return EDIT;
	}
	
	
	public void setShopManager(ShopManager shopManager) {
		this.shopManager = shopManager;
	}
	public ShopManager getShopManager() {
		return shopManager;
	}
	public void setShop(Shop shop) {
		this.shop = shop;
	}
	public Shop getShop() {
		return shop;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setContentImageManager(ContentImageManager contentImageManager) {
		this.contentImageManager = contentImageManager;
	}

	public ContentImageManager getContentImageManager() {
		return contentImageManager;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getId() {
		return id;
	}

}
